package com.jjwxc.jwjskandriod.activity;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.adapter.SimilarityViewHolder;
import com.jjwxc.jwjskandriod.config.BaseActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshView;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshViewFooter;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.BookListSimilarResponse;
import com.jjwxc.jwjskandriod.model.DetailsBookResponse;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.jjwxc.jwjskandriod.widget.GroupPop;
import com.jjwxc.jwjskandriod.widget.LinearLayouDecoration;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import jp.wasabeef.glide.transformations.BlurTransformation;
import jp.wasabeef.glide.transformations.CropTransformation;

public class SimilarityActivity extends BaseActivity {
    private RecyclerView rv_similarity;
    private SimilarityAdapter adapter;
    private TextView tv_fag_one;
    private TextView tv_fag_two;
    private TextView tv_fag_three;
    private TextView tv_fag_four;
    private ImageView img_suggest_book;
    private LinearLayout ll_head_bg;

    private TextView tv_suggest_name;
    private TextView tv_fag;
    private LinearLayout ll_fag;

    private String author;
    private String authorId;

    private XRefreshView refreshView;
    public static long lastRefreshTime;

    private int page = 0;

    private String bookId;

    @Override
    public int getContentViewId() {
        return R.layout.activity_similarity;
    }

    @Override
    public void findView() {
        setNoTitle();
        rv_similarity = findViewById(R.id.rv_similarity);
        tv_fag_one = findViewById(R.id.tv_fag_one);
        tv_fag_two = findViewById(R.id.tv_fag_two);
        tv_fag_three = findViewById(R.id.tv_fag_three);
        tv_fag_four = findViewById(R.id.tv_fag_four);
        tv_suggest_name = findViewById(R.id.tv_suggest_name);
        img_suggest_book = findViewById(R.id.img_suggest_book);
        tv_fag = findViewById(R.id.tv_fag);
        ll_fag = findViewById(R.id.ll_fag);
        ll_head_bg = findViewById(R.id.ll_head_bg);

        refreshView = findViewById(R.id.refreshView);
    }

    @Override
    public void setListener() {
        ll_fag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SimilarityActivity.this, AuthorActivity.class);
                intent.putExtra("author_name", author);
                intent.putExtra("author_id", authorId);
                startActivity(intent);
            }
        });

        refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                page = 0;
                listSimilarBook(bookId, page);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page += 1;
                listSimilarBook(bookId, page * 10);
            }
        });
    }

    @Override
    public void afterCreate() {
        bookId = getIntent().getStringExtra("bookId");
        rv_similarity.setNestedScrollingEnabled(false);
        rv_similarity.setFocusable(false);
        rv_similarity.setLayoutManager(new LinearLayoutManager(SimilarityActivity.this));
        rv_similarity.addItemDecoration(new LinearLayouDecoration(SimilarityActivity.this,
                LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));
        rv_similarity.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
        adapter = new SimilarityAdapter(this);
        rv_similarity.setAdapter(adapter);

        refreshView.setPinnedTime(1000);
        refreshView.setMoveForHorizontal(true);
        refreshView.setPullRefreshEnable(true);
        refreshView.setPullLoadEnable(true);
        refreshView.setAutoLoadMore(true);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(SimilarityActivity.this));
        refreshView.enableReleaseToLoadMore(true);
        refreshView.enableRecyclerViewPullUp(true);
        refreshView.enablePullUpWhenLoadCompleted(true);
        // 設置上次刷新的時間
        refreshView.restoreLastRefreshTime(lastRefreshTime);

        listSimilarBook(bookId, page);
        bookDetail(bookId);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onEvent(this, UMConstant.PAGE_SIMILAR_BOOK_RECOMMEND);
    }

    public void bookDetail(String bookId) {
        post(Url.bookDetail, "", DetailsBookResponse.class, new FFNetWorkCallBack<DetailsBookResponse>() {
            @Override
            public void onSuccess(DetailsBookResponse response) {
                if (response.getCode() == 200) {
                    DetailsBookResponse.DataBean mResponse = response.getData();
                    tv_suggest_name.setText(mResponse.getName());
                    tv_fag.setText(mResponse.getAuthor());
                    author=mResponse.getAuthor();
                    authorId=mResponse.getAuthorId();
                    String category=mResponse.getCategory();
                    String[] list= category.split("-");
                    //不是青少年模式
                    if (!PreUtils.getBoolean("QING_switch", false)) {
                        if (list.length > 3) {
                            tv_fag_four.setVisibility(View.VISIBLE);
                            tv_fag_three.setVisibility(View.VISIBLE);
                            tv_fag_two.setVisibility(View.VISIBLE);
                            tv_fag_one.setVisibility(View.VISIBLE);
                            tv_fag_one.setText(list[0]);
                            tv_fag_two.setText(list[1]);
                            tv_fag_three.setText(list[2]);
                            tv_fag_four.setText(list[3]);
                        } else if (list.length == 3) {
                            tv_fag_one.setText(list[0]);
                            tv_fag_two.setText(list[1]);
                            tv_fag_three.setText(list[2]);
                            tv_fag_three.setVisibility(View.VISIBLE);
                            tv_fag_two.setVisibility(View.VISIBLE);
                            tv_fag_one.setVisibility(View.VISIBLE);
                            tv_fag_four.setVisibility(View.GONE);
                        } else if (list.length == 2) {
                            tv_fag_one.setText(list[0]);
                            tv_fag_two.setText(list[1]);
                            tv_fag_four.setVisibility(View.GONE);
                            tv_fag_three.setVisibility(View.GONE);
                            tv_fag_two.setVisibility(View.VISIBLE);
                            tv_fag_one.setVisibility(View.VISIBLE);
                        } else if (list.length == 1) {
                            tv_fag_one.setText(list[0]);
                            tv_fag_one.setVisibility(View.VISIBLE);
                            tv_fag_four.setVisibility(View.GONE);
                            tv_fag_three.setVisibility(View.GONE);
                            tv_fag_two.setVisibility(View.GONE);
                        }
                    } else {
                        tv_fag_one.setText("童话的书");
                        tv_fag_four.setVisibility(View.GONE);
                        tv_fag_three.setVisibility(View.GONE);
                        tv_fag_two.setVisibility(View.GONE);
                        tv_fag_one.setVisibility(View.GONE);
                    }
                    FFImageLoader.loadImage(SimilarityActivity.this, img_suggest_book, mResponse.getCoverImgUrl(), mResponse.getBookId(), true);
                    MultiTransformation multi = new MultiTransformation(
                            new BlurTransformation(15),
                            new CropTransformation(200, 100, CropTransformation.CropType.TOP));
                    //Glide实现图片高斯模糊
                    Glide.with(SimilarityActivity.this).load(mResponse.getCoverImgUrl())
                            .apply(bitmapTransform(multi)).into(new SimpleTarget<Drawable>() {
                                @Override
                                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                    ll_head_bg.setBackground(resource);// 设置背景
                                }
                            });
                }
            }

            @Override
            public boolean onFail(DetailsBookResponse response) {
                return false;
            }
        }, "{\"bookId\":\"" + bookId + "\"}");
    }

    public void listSimilarBook(String bookId, int page) {
        String request = "{\"offset\":" + page + ",\"limit\":10,\"bookId\":\"" + bookId + "\"}";

        post(Url.listSimilarBook, null, BookListSimilarResponse.class, new FFNetWorkCallBack<BookListSimilarResponse>() {
            @Override
            public void onSuccess(BookListSimilarResponse response) {
                /*if (response.getCode() == 200) {
                    adapter.setData(response.getData());
                }*/
                lastRefreshTime = refreshView.getLastRefreshTime();
                if (response.getCode() == 200) {
                    if (response.getData() == null || response.getData().size() < 10) {
                        refreshView.setLoadComplete(true);
                    }
                    if (page == 0) {
                        refreshView.stopRefresh();
                        refreshView.setLoadComplete(false);
                        adapter.setData(response.getData());
                    } else {
                        refreshView.stopLoadMore();
                        adapter.addData(response.getData());
                    }
                }
            }

            @Override
            public boolean onFail(BookListSimilarResponse response) {
                refreshView.stopLoadMore();
                refreshView.stopRefresh();
                refreshView.setLoadComplete(true);
                return false;
            }
        }, request);
    }

    public class SimilarityAdapter extends BaseRecyclerAdapter<SimilarityViewHolder> {
        private Context context;


        private List<BookListSimilarResponse.DataBean> mData = new ArrayList<>();


        public SimilarityAdapter(Context cnt) {
            this.context = cnt;

        }

        public void addData(List<BookListSimilarResponse.DataBean> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<BookListSimilarResponse.DataBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public SimilarityViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.similarity_item, parent, false);
            SimilarityViewHolder viewHolder_text = new SimilarityViewHolder(mView);
            return viewHolder_text;

        }

        @Override
        public SimilarityViewHolder getViewHolder(View view) {
            return new SimilarityViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @Override
        public void onBindViewHolder(final SimilarityViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {
            FFImageLoader.loadImage(context, holder.img_similarity_item, mData.get(position).getCoverImgUrl(), mData.get(position).getBookId(), true);
            holder.tv_bookname.setText(mData.get(position).getName());
            holder.tv_book_author.setText(mData.get(position).getAuthor());
            holder.tv_book_text.setText(StUtils.reBlank(mData.get(position).getBookShortIntro()));
            holder.tv_similarity_tab.setText(mData.get(position).getChannlname());
            if (mData.get(position).getIsInBookcase()) {
                holder.tv_collet.setBackgroundResource(R.drawable.collect_law_false);
                holder.tv_collet.setText("已收藏");
            } else {
                holder.tv_collet.setBackgroundResource(R.drawable.collect_law_true);
                holder.tv_collet.setText("加入收藏");
            }
            holder.cl_similarity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SimilarityActivity.this, BookDetailsActivity.class);
                    intent.putExtra("bookId", mData.get(position).getBookId());
                    startActivity(intent);
                }
            });
            holder.tv_collet.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mData.get(position).getIsInBookcase()) {
                        FFApplication.showToast("已收藏");
                        return;
                    }
                    GroupPop.collentGroupPop(v, SimilarityActivity.this, group -> {
                        if (group==null) {
                            return;
                        }
                       post(Url.addBookcase, null, String.class, new FFNetWorkCallBack<String>() {
                            @Override
                            public void onSuccess(String response) {
                                if (response.contains("200")) {
                                    mData.get(position).setIsInBookcase(true);
                                    holder.tv_collet.setBackgroundResource(R.drawable.collect_law_false);
                                    holder.tv_collet.setText("已收藏");
                                    notifyItemChanged(position);
                                    FFApplication.showToast("收藏成功");
                                }
                            }

                            @Override
                            public boolean onFail(String response) {
                                return false;
                            }
                        }, "{\"bookId\":\"" + mData.get(position).getBookId() + "\",\"bookcaseGroupId\":\"" + group + "\"}");

                    });
                }
            });

        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }

    }
}
